using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Robot.Business;
using Robot.Data;
using Robot.Entities;
using DevExpress.Web.ASPxGridView;
using Scb.Framework;
using System.IO;
using WebRobot.App_code;

namespace WebRobot.Pages
{
  public partial class ViewTransaction : BasePage
  {

    #region Event

    protected void Page_Load(object sender, EventArgs e)
    {

      if (!IsPostBack)
      {
        if (dateFrom.Value == null)
        {
          dateFrom.Value = DateTime.Today;
        }
        if (dateTo.Value == null)
        {
          dateTo.Value = DateTime.Now;
        }
      }
      if (IsPostBack)
      {
        LoadWithDate();
      }

    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {

    }

    protected void gvViewTran_PageIndexChanged(object sender, EventArgs e)
    {
      LoadWithDate();
    }

    protected void btnCheckRule_Click(object sender, EventArgs e)
    {
      if (tblInternalRateService.GettblInternalRateList(tblInternalRateColumns.CreatedBy, OrderDirection.ASC).Count > 0 && tblInternalRateService.GettblInternalRateList(tblInternalRateColumns.CreatedDate, OrderDirection.DESC)[0].CreatedDate.Value.CompareTo(DateTime.Today) == 0)
      {
        if (gvViewTran.VisibleRowCount > 0)
        {
          CheckAllRule((tblImportTransactionCollection)gvViewTran.DataSource);
          ViewRule(true);
          try
          {
            tblImportTransactionCollection dataSource = new tblImportTransactionCollection();

            LoadWithDate();
            int passRuleNo = 0;
            for (int i = 0; i < gvViewTran.VisibleRowCount; i++)
            {
              if (PassAllRule((tblImportTransaction)gvViewTran.GetRow(i)))
              {
                gvViewTran.Selection.SetSelection(i, true);
                passRuleNo++;
              }
            }

            PassRuleNo.InnerHtml = passRuleNo.ToString();
            btnCheckAll.Enabled = true;
            btnSubmit.Enabled = true;
            btnUnCheckALL.Enabled = true;
            lbStatus.InnerHtml = "Check rule successful!";
            lbStatus.Style.Add(HtmlTextWriterStyle.Color, "Blue");
          }
          catch (Exception ex)
          {
            Logger.Error("WebRobot.Pages.ViewTransaction::btnCheckRule_Click", ex);
          }
        }
        else
        {
          lbStatus.InnerHtml = "No transaction selection!";
          lbStatus.Style.Add(HtmlTextWriterStyle.Color, "Red");
        }
      }
      else
      {
        lbStatus.InnerHtml = @"<a href='../Pages/ImportRatePage.aspx'>You should upload internal rate before check rule! </a>";
        lbStatus.Style.Add(HtmlTextWriterStyle.Color, "Red");
      }


    }

    protected void btnCheckAll_Click(object sender, EventArgs e)
    {
      gvViewTran.Selection.SelectAll();
    }

    protected void btnUnCheckALL_Click(object sender, EventArgs e)
    {
      gvViewTran.Selection.UnselectAll();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
      try
      {
        tblImportTransactionCollection list = new tblImportTransactionCollection();
        list.AddRange((tblImportTransactionCollection)gvViewTran.DataSource);
        int countSubmit = 0;
        for (int i = 0; i < gvViewTran.VisibleRowCount; i++)
        {
          if (gvViewTran.Selection.IsRowSelected(i))
          {

            tblImportTransaction tran = (tblImportTransaction)gvViewTran.GetRow(i);
            list.Remove(tran);
            tran.Status = 1; // submited
            tblImportTransactionService.UpdatetblImportTransactionStatus(tran);
            countSubmit++;
          }
        }
        gvViewTran.DataSource = list;
        gvViewTran.DataBind();
        lbStatus.InnerHtml = "Submit successful " + countSubmit.ToString() + " transaction!";
        lbStatus.Style.Add(HtmlTextWriterStyle.Color, "Blue");
      }
      catch (Exception ex)
      {
        Logger.Error("WebRobot.Pages.ViewTransaction::btnSubmit_Click", ex);
        lbStatus.InnerHtml = "Submit error!";
        lbStatus.Style.Add(HtmlTextWriterStyle.Color, "Red");
      }
    }

    protected void gvViewTran_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
    {
      if (e.RowType != DevExpress.Web.ASPxGridView.GridViewRowType.EmptyDataRow && e.RowType != DevExpress.Web.ASPxGridView.GridViewRowType.Group)
      {
        if (e.Row.Cells.Count > 8 && e.GetValue("Rule2") != null)
        {

          if (e.GetValue("Rule2").ToString() == "0" || e.GetValue("Rule3").ToString() == "0" || e.GetValue("Rule4").ToString() == "0" || e.GetValue("Rule5").ToString() == "0")
          {
            e.Row.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
          }
        }

      }
    }

    #endregion  

    #region Helper

    private string GetOpicsCode(string CustomerName, string sBranch)
    {
      if (CustomerName == "")
      {
        CustomerName = "Wholesale Banking";
      }
      string opicsCode = "";
      opicsCode = tblOpicCodeService.GettblOpicCode(CustomerName, sBranch).OpicsCode;
      return opicsCode;
    }

    private string GetPortfolio(string CustomerName, string sBranch)
    {
      if (CustomerName == "")
      {
        CustomerName = "Wholesale Banking";
      }
      string opicsCode = "";
      opicsCode = tblOpicCodeService.GettblOpicCode(CustomerName, sBranch).Portfolio;
      return opicsCode;
    }

    private int LoadDataToGrid(DateTime from, DateTime to)
    {
      int countRow = 0;
      if (to.CompareTo(from) >= 0)
      {
        gvViewTran.DataSource = tblImportTransactionService.GetImportTransactionUnSubmitByCreatedDate(from, to, CurrentUser.Peoplewise);
        gvViewTran.DataBind();
        gvViewTran.Visible = true;
        if (dateFrom.Value == null)
        {
          dateFrom.Value = from;
          dateTo.Value = to;
        }
        countRow = gvViewTran.VisibleRowCount;
      }
      return countRow;
    }

    private void LoadWithDate()
    {
      try
      {
        string sfrom = "";
        string sto = "";
        sfrom = dateFrom.Value.ToString();
        sto = dateTo.Value.ToString();

        if (dateFrom.Value != null && dateTo.Value != null)
        {
          DateTime from = DateTime.Parse(dateFrom.Value.ToString());
          DateTime to = DateTime.Parse(dateTo.Value.ToString());
          LoadDataToGrid(from, to);


        }

        if (gvViewTran.VisibleRowCount > 0)
        {
          btnCheckRule.Enabled = true;
        }
        if (dateFrom.Value == null)
        {
          dateFrom.Value = sfrom;

        }
        if (dateTo.Value == null)
        {
          dateTo.Value = sto;
        }
      }
      catch (Exception ex)
      {
        Logger.Error("WebRobot.Pages.ViewTransaction::Page_Load", ex);
        Response.Redirect("UploadedData.aspx");
      }
    }

    private bool PassAllRule(tblImportTransaction tran)
    {
      if (tran.Rule1 == 0 || tran.Rule2 == 0 || tran.Rule4 == 0 || tran.Rule3 == 0 || tran.Rule5 == 0)
      {
        return false;
      }
      return true;
    }

    private void ViewRule(bool isView)
    {
      gvViewTran.Columns["Rule2"].Visible = isView;
      gvViewTran.Columns["Rule3"].Visible = isView;
      gvViewTran.Columns["Rule4"].Visible = isView;
      gvViewTran.Columns["Rule5"].Visible = isView;
      gvViewTran.Columns["Check"].Visible = isView;
    }

    #endregion

    #region Check rule

    #region Check All Rule

    private void CheckAllRule(tblImportTransactionCollection listTran)
    {
      foreach (tblImportTransaction tran in listTran)
      {
        tran.Exception = "";
      //  CheckRuleValueDate(tran);//rule 1
        CheckRuleUSD100K(tran);//rule 2
        CheckRuleCurrency(tran);//rule 3
        CheckRuleRateUSDVND(tran);//rule 4
        CheckRuleInternalBoardRate(tran);//rule 5
      }
    }

    #endregion

    //#region Check rule ValueDate: Rule 1

    //private void CheckRuleValueDate(tblImportTransaction tran)
    //{
    //  DateTime toDay = DateTime.Now;
    //  try
    //  {
    //    if (tran.ValueDate.Value.Date.CompareTo(toDay.Date) == 0)
    //    {
    //      tran.Rule1 = 1;
    //    }
    //    else
    //    {
    //      tran.Rule1 = 0;
    //      tran.Exception = tran.Exception + "Rule1: Valuedate: " + tran.ValueDate.Value.Date.ToString("dd/MM/yyyy") + "<>" + toDay.Date.ToString("dd/MM/yyyy");

    //    }
    //    tblImportTransactionService.UpdatetblImportTransactionRule(tran);

    //  }
    //  catch (Exception ex)
    //  {
    //    Logger.Error("WebRobot.Pages.ViewTransaction::CheckRuleValueDate", ex);
    //    throw;
    //  }

    //}

    //#endregion

    #region Check rule USD amount > 20K: Rule 2

    private void CheckRuleUSD100K(tblImportTransaction tran)
    {

      tblOpicsTransaction opicsTran = new tblOpicsTransaction();
      try
      {
        if (tran.BuyCurrency.Contains("USD") && tran.BuyAmount.Value >= 20000)
        {
          tran.Rule2 = 0;
          tran.Exception = tran.Exception + "::Rule2: USD Buy amount: " + tran.BuyAmount.Value.ToString("N2") + " > 20k";
        }
        else if (tran.SellCurrency.Contains("USD") && tran.SellAmount.Value >= 20000)
        {
          tran.Rule2 = 0;
          tran.Exception = tran.Exception + "::Rule2: USD Sell amount: " + tran.SellAmount.Value.ToString("N2") + " > 20k";
        }
        else
        {
          tran.Rule2 = 1;
        }
        tblImportTransactionService.UpdatetblImportTransactionRule(tran);
      }
      catch (Exception ex)
      {
        Logger.Error("WebRobbot.Pages.ViewTransaction::CheckRuleUSD20k", ex);
      }


    }

    #endregion

    #region Check rule Currency in Opics: Rule 3

    private void CheckRuleCurrency(tblImportTransaction tran)
    {

      try
      {
        tblCurrencyInOpic cCY = new tblCurrencyInOpic();
        cCY = tblCurrencyInOpicService.GettblCurrencyInOpicByCCY(tran.BuyCurrency, tran.SellCurrency);

        if (cCY != null)
        {
          tran.Rule3 = 1;
        }
        else
        {
          tran.Rule3 = 0;
          tran.Exception = tran.Exception + "::Rule3: Currency " + tran.BuyCurrency + tran.SellCurrency + " not in Opics";
        }
        tblImportTransactionService.UpdatetblImportTransactionRule(tran);
      }
      catch (Exception ex)
      {
        Logger.Error("WebRobot.Pages.ViewTransaction::CheckRuleCurrency", ex);
      }
    }

    #endregion

    #region Check Rule USDVND Rate: Rule 4

    private void CheckRuleRateUSDVND(tblImportTransaction tran)
    {
      tblOpicsTransaction opicsTran = new tblOpicsTransaction();
      try
      {
        if (tran.BuyCurrency.Contains("USD") && tran.SellCurrency.Contains("VND"))
        {

          tblInternalRate rateRef = new tblInternalRate();
          rateRef = tblInternalRateService.GetInternalRateByCurrency(tran.BuyCurrency, tran.SellCurrency);

          if (rateRef.CeilingRate.Value != -1)
          {
            if (tran.CusRate.Value > rateRef.CeilingRate.Value)
            {
              tran.Rule4 = 0;
              tran.Exception = tran.Exception + "::Rule4: USDVND " + tran.CusRate.Value.ToString("N2") + " > " + rateRef.CeilingRate.Value.ToString("c2");
            }
            else if (tran.CusRate.Value < rateRef.FloorRate.Value)
            {
              tran.Rule4 = 0;
              tran.Exception = tran.Exception + "::Rule4: USDVND " + tran.CusRate.Value.ToString("N2") + " < " + rateRef.FloorRate.Value.ToString("c2");
            }
            else
            {
              tran.Rule4 = 1;
            }
            tblImportTransactionService.UpdatetblImportTransactionRule(tran);

          }
        }
        else
        {
          tran.Rule4 = 1;

          tblImportTransactionService.UpdatetblImportTransactionRule(tran);
        }
      }
      catch (Exception ex)
      {
        Logger.Error("WebRobbot.Pages.ViewTransaction::CheckRuleRateUSDVND", ex);
      }

    }

    #endregion

    #region Check Rule Internal, Board Rate: Rule 5

    private void CheckRuleInternalBoardRate(tblImportTransaction tran)
    {
      tblOpicsTransaction opicsTran = new tblOpicsTransaction();
      try
      {
        tblInternalRate rateRef = new tblInternalRate();
        rateRef = tblInternalRateService.GetInternalRateByCurrency(tran.BuyCurrency, tran.SellCurrency);

        if (rateRef.CeilingRate.Value != -1)
        {
          if (tran.CusRate.Value > rateRef.CeilingRate.Value)
          {
            tran.Rule5 = 0;
            tran.Exception = tran.Exception + "::Rule5: Rate between " + tran.CusRate.Value.ToString("N2") + " > " + rateRef.CeilingRate.Value.ToString("c2");
          }
          else if (tran.CusRate.Value < rateRef.FloorRate.Value)
          {
            tran.Rule5 = 0;
            tran.Exception = tran.Exception + "::Rule5: Rate between " + tran.CusRate.Value.ToString("N2") + " < " + rateRef.FloorRate.Value.ToString("c2");
          }
          else
          {
            tran.Rule5 = 1;
          }
          tblImportTransactionService.UpdatetblImportTransactionRule(tran);
        }
      }
      catch (Exception ex)
      {
        Logger.Error("WebRobbot.Pages.ViewTransaction::CheckRuleInternalRate", ex);
      }

    }

    #endregion

    #endregion

  }
}
